<template>
  <div class="home">
    <ToolBar />
    <div class="home-content">
      <div class="home-logo">
        <img class="logo" src="../assets/logo_big.png" alt="logo text" />
        <el-button type="primary" class="btn add" @click="clickCreate">新建</el-button>
        <el-button type="primary" class="btn open" @click="clickOpen">打开</el-button>
      </div>
      <div class="home-main">
        <div v-for="(item, index) in books" :key="index" class="books-box">
          <div v-if="item.children && item.children.length" class="books-category">{{ item.name }}</div>
          <div ref="booksMain" class="books-main">
            <div :style="{ width: booksListWidth + 'px' }" class="books-list">
              <template v-for="(it, idx) in item.children" :key="idx">
                <div v-if="it.type === 'directory'" class="books-item" @click="clickBook(it)" @contextmenu="handleContextmenu($event, it)">
                  {{ it.name }}
                </div>
              </template>
            </div>
          </div>
        </div>
        <p v-if="books.length === 0" class="no-data">书架暂无书籍～</p>
      </div>
    </div>
  </div>
  <CreateBook v-model:visible="createVisible" :editBook="editBook" @onCreatedBook="init" />
  <SetWorkPath v-if="setWorkPathVisible" v-model:visible="setWorkPathVisible" />
  <ContextMenu v-model:visible="showContextMenu" :menu="contextMenu" :position="contextMenuPosition" @clickContextMenu="handleClickContextMenu" />
</template>

<script setup lang="ts">
/**
 * 首页
 */
import { ref, reactive, computed, onMounted } from "vue";
import { useGlobalStore } from "@/store/modules/globalStore";
import "element-plus/es/components/message-box/style/css";
import "element-plus/es/components/message/style/css";
import { ElMessageBox, ElMessage } from "element-plus";

const globalStore = useGlobalStore();

interface Book {
  type: string;
  name: string;
  path: string;
  children?: Book[];
}
interface EditBook {
  name: string;
  genre: string;
  summary: string;
}
interface ContextNodeData {
  data?: Book;
}
// 所有书籍
const books = ref<Book[]>([]);
const editBook = ref<EditBook>({ name: "", genre: "", summary: "" });
const createVisible = ref(false);
const setWorkPathVisible = ref(false);
// 右键菜单列表
const contextMenu = ref([
  { key: "edit", name: "编辑" },
  { key: "delete", name: "删除" }
]);
// 是否展示右键菜单
const showContextMenu = ref(false);
// 右键菜单显示时的位置坐标
const contextMenuPosition = ref({ x: 0, y: 0 });
// 右键点击聚焦的节点数据
const contextNodeData = reactive<ContextNodeData>({});

// 软件打开后先读本地配置数据，如果没有，弹出设置基础工作目录窗口
async function init() {
  let workPath = await window.electronAPI.getStore("workPath");
  if (!workPath) {
    setWorkPathVisible.value = true;
    return;
  }

  globalStore.setWorkPath(workPath);

  // 读取当前工作区目录下的所有文件
  const allFiles: any = await window.electronAPI.readdir(workPath);
  console.log(allFiles);
  books.value = [];
  for (let i = 0; i < allFiles.length; i++) {
    const ele = allFiles[i];
    if (ele.type === "directory") {
      books.value.push(ele);
    }
  }
}

onMounted(() => {
  init();
});

// 处理书籍右键菜单项点击，编辑，删除
const handleClickContextMenu = async (key: string) => {
  showContextMenu.value = false;
  if (key === "edit") {
    if (contextNodeData.data) {
      // 读取编辑书籍对应的配置文件mzBook.json
      const res = await window.electronAPI.readFile(contextNodeData.data.path + "/mzBook.json");
      if (res) {
        editBook.value = JSON.parse(res);
        createVisible.value = true;
      }
    }
  } else if (key === "delete") {
    // 删除指定目录内容
    ElMessageBox.confirm("你确认要删除这本书吗?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        if (contextNodeData.data) {
          const res = await window.electronAPI.rmdir(contextNodeData.data.path);
          if (res) {
            init();
          }
          ElMessage({
            type: "success",
            message: "已删除该书籍"
          });
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除该书籍"
        });
      });
  }
};

// 点击新建书籍
function clickCreate() {
  // 如果当前工作目录内没有任何书籍数据，弹出设置基础工作目录窗口
  if (books.value.length === 0 && !globalStore.workPath) {
    setWorkPathVisible.value = true;
  } else {
    editBook.value = { name: "", genre: "", summary: "" };
    createVisible.value = true;
  }
}

// 点击打开，打开系统文件夹，导入可用数据
function clickOpen() {
  console.log("打开文件夹");
}

// 书籍列表容器宽度，根据书本数量动态计算
const booksListWidth = computed(() => {
  return (books.value.length + 1) * (148 + 20) - 20;
});

// 右键点击书籍，弹出右键关联菜单，编辑，删除等操作
function handleContextmenu(e: any, data: any) {
  contextNodeData.data = data;
  showContextMenu.value = true;
  contextMenuPosition.value = {
    x: e.x || e.pageX,
    y: e.y || e.pageY
  };
}

// 点击书籍，打开书籍内容编辑窗口
function clickBook(e: any) {
  window.electronAPI.openWin("/editer/index?path=" + e.path);
}
</script>

<style lang="scss" scoped>
.home {
  padding: 20px 20px 20px 80px;
  &-logo {
    text-align: center;
    position: relative;
    .logo {
      display: block;
      height: 70px;
      margin: 0 auto;
    }
    .btn {
      position: absolute;
      right: 0px;
      top: 50%;
      transform: translateY(-50%);
      &.add {
        right: 80px;
      }
    }
  }
  &-main {
    overflow: auto;
    .no-data {
      font-size: 36px;
      text-align: center;
      position: absolute;
      top: 50%;
      left: calc(50% + 30px);
      transform: translate(-50%, -50%);
      color: var(--el-color-info);
    }
    .books {
      &-box {
        width: 100%;
        padding: 20px 0px;
        border-bottom: 1px solid var(--el-border-color);
        display: flex;
        align-items: center;
        &:last-of-type {
          margin-bottom: 0px;
        }
      }
      &-category {
        width: 24px;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
        margin-right: 10px;
      }
      &-main {
        overflow: auto;
      }
      &-list {
        min-width: calc(100vw - 134px);
        overflow: hidden;
        height: 208px;
        position: relative;
      }
      &-item {
        float: left;
        width: 148px;
        height: 100%;
        border: 1px solid #ccc;
        border-radius: 10px;
        font-size: 24px;
        writing-mode: vertical-rl;
        cursor: pointer;
        box-sizing: border-box;
        padding: 15px 10px;
        margin-right: 20px;
        transition: 0.3s;
        background-color: #144a74;
        color: #fff;
        overflow: hidden;
        &:hover {
          background-color: var(--el-color-primary);
        }
      }
    }
  }
}
</style>
